package com.yuan.springcloud.product.controller;

import com.yuan.springcloud.product.entity.Product;
import com.yuan.springcloud.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YouYuan
 * @version 1.0
 * @date 2020/3/25 3:49
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Value("${server.port}")
    private String port;

    @Value("${spring.cloud.client.ip-address}")
    private String ip;// 自动注入SpringCloud获取到的当前应用的IP地址

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Product findById(@PathVariable Long id) throws InterruptedException {
//        Thread.sleep(1000L);
        Product product = productService.findById(id);
        product.setProductDesc(product.getProductDesc() + " 来自于" + ip + ":" + port);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        System.out.println(request.getParameterMap());
        return product;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@RequestBody Product product){
        productService.save(product);
        return "保存成功";
    }

    @RequestMapping(value = "/msg", method = RequestMethod.GET)
    public String msg(String msg){
        String message = ip + ":" + port + "收到消息:" + msg;
        System.out.println(message);
        return message;
    }
}
